import { airportCityListReq } from '@/common/api'
import { ERR_MES } from '@/common/constant'
import tools from '@/common/tools'
import { ScrollView, View } from '@tarojs/components'
import { useEffect, useState } from 'react'
import './airportList.scss'
import CityItem from './components/CityItem'

export default function AirportList() {
  // 处理之后的城市列表
  const [cityListObj, setCityListObj] = useState({})
  // 字母列表
  const [letterList, setLetterList] = useState([])
  // 当前选中的字母
  const [currentLetter, setCurrentLetter] = useState('')

  useEffect(() => {
    getCityList()
  }, [])

  const getCityList = async () => {
    tools.showLoading()
    try {
      const { result } = await airportCityListReq()
      const obj = formatList(result)
      setCityListObj(obj)
      setLetterList(Object.keys(obj))
    } catch (error) {
      tools.showToast(ERR_MES)
    } finally {
      tools.hideLoading()
    }
  }

  const formatList = list => {
    const obj = {}
    if (list?.length) {
      list.map(ele => {
        const { firstLetter } = ele
        // 判断obj中是否有以firstLetter为键的属性
        if (!obj[firstLetter]) {
          obj[firstLetter] = []
        }
        obj[firstLetter].push(ele)
      })
    }
    return obj
  }

  const onLetterClick = letter => {
    setCurrentLetter(letter)
  }

  return (
    <View className="airport-list-container">
      <ScrollView
        scrollY
        scrollWithAnimation={tools.isAliPay ? false : true}
        style={{ height: '100vh' }}
        scrollIntoView={currentLetter}
      >
        {letterList?.map(item => {
          const cityList = cityListObj[item]
          return <CityItem key={item} label={item} cityList={cityList} />
        })}
      </ScrollView>
      <View className="letter-container">
        {letterList?.map(item => (
          <View key={item} className="letter-item" onClick={() => onLetterClick(item)}>
            {item}
          </View>
        ))}
      </View>
    </View>
  )
}
